package com.springboot.framework.config.redis;

import com.springboot.framework.exception.BaseException;
import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RedisMybatisCache implements Cache {

    private final Logger logger = LoggerFactory.getLogger(RedisMybatisCache.class);

    private static RedisTemplate redisTemplate;

    private String id;

    private final ReadWriteLock rwl = new ReentrantReadWriteLock();

    /**
     * 初始化缓存
     * @param id
     */
    public RedisMybatisCache(String id){
        if (id == null)
            throw new BaseException("mybatis缓存初始化需要一个id");
        this.id = id;
    }

    public static void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisMybatisCache.redisTemplate = redisTemplate;
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public void putObject(Object o, Object o1) {
        try{
            redisTemplate.opsForValue().set(o.toString(),o1);
        }catch(Exception e){
            e.printStackTrace();
            logger.info("添加到mybatis缓存失败");
        }
    }

    @Override
    public Object getObject(Object o) {
        try{
            return redisTemplate.opsForValue().get(o.toString());
        }catch(Exception e){
            e.printStackTrace();
            logger.info("获取mybatis缓存失败");
        }
        return null;
    }

    @Override
    public Object removeObject(Object o) {
        try{
            redisTemplate.delete(o.toString());
        }catch(Exception e){
            e.printStackTrace();
            logger.info("从mybatis缓存移除失败");
        }
        return null;
    }

    @Override
    public void clear() {
        try{
            redisTemplate.delete(getId());
        }catch (Exception e){
            logger.info("刷新mybatis失败");
        }
    }

    @Override
    public int getSize() {
        return redisTemplate.keys("*").size();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return rwl;
    }
}
